﻿using Cofe.Core.Entry;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Cofe.Core.Security;

namespace Cofe.Core
{
    public static class EntryListFE
    {
        public static ICustomEntryList NewEntryList(string name = null)
        {
            var ec = CofeServices.EntryConstructor;
            return ec.ConstructEntry<ICustomEntryList>(ec.ConstructPropertyHost(
                new CustomEntryListPrimaryPP(name, false)));
        }

        public static async Task<ICustomEntryList> MakeParsbleAsync(this ICustomEntryList entryList,
            PermissionType permissionType = PermissionType.All)
        {
            var existingEntry = (await EntryFE.TryParsePathAsync("{" + entryList.Name + "}"));
            if (existingEntry != null)
            {
                if (existingEntry.Is<ICustomEntryList>())
                    return existingEntry.As<ICustomEntryList>();
                else throw new InvalidOperationException("Volume already created but not as ICustomEntryList.");
            }

            await VolumeFE.MapAsync(permissionType, "EntryList", entryList.Name, "");
#if DEBUG
            if (CofeServices.VolumeRegistrar.LookupVolume(entryList.Name) == null)
                throw new Exception();
#endif
            var newEntryList = (await EntryListFE.FromPathAsync("{" + entryList.Name + "}")).As<ICustomEntryList>();

            await CofeServices.TransferManager.TransferAsync(TransferMode.Copy, entryList.EnumerateCofeSystemInfos().ToArray(),
                entryList, newEntryList, null, System.Threading.CancellationToken.None);

            return newEntryList;
        }

        public static async Task<IEntryList> FromPathAsync(string path)
        {
            var retVal = (await EntryFE.TryParsePathAsync(path, ParsableType.ParsePathLookup, EntryConstructionFlags.DefaultWithLookup));
            if (retVal != null)
                return retVal.As<IEntryList>();
            return null;
        }
    }
}
